package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.OrderConfigMapper;
import com.qingcheng.dao.OrderItemMapper;
import com.qingcheng.dao.OrderLogMapper;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.*;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.service.pay.WeixinPayService;
import com.qingcheng.utils.IdWorker;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;


import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 返回全部记录
     *
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 条件查询
     *
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = null;
        if (searchMap.get("ids") == null) {
            example = createExample(searchMap);
        } else {
            example = new Example(Order.class);
            List<String> list = new ArrayList<String>();
            Example.Criteria criteria = example.createCriteria();
            JSONArray ids = (JSONArray) searchMap.get("ids");
            for (int i = 0; i < ids.size(); i++) {
                list.add(ids.getString(i));
            }
            criteria.andIn("id", list);
           /* example = new Example(Order.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("id",Arrays.asList((String[])searchMap.get("ids")));*/
        }
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(), orders.getResult());
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }


    @Autowired
    private CartService cartService;
    @Reference
    private SkuService skuService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 新增
     *
     * @param order
     */
    @Override
    public Map<String, Object> add(Order order) {

        //1.获取选中购物车
        //获取购物车(刷新单价)
        List<Map<String, Object>> cartList = cartService.findNewOrderItemList(order.getUsername());
        //获取选中的购物车
        List<OrderItem> orderItemList = cartList.stream()
                .filter(cart -> (boolean) cart.get("checked"))
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());
        //2.扣减库存
        if (!skuService.deductionStock(orderItemList)) {
            throw new RuntimeException("库存扣减失败");
        }
        //3.保存订单主表
        try {
            order.setId(idWorker.nextId() + "");
            //合计数计算
            IntStream numStream = orderItemList.stream().mapToInt(OrderItem::getNum);
            IntStream moneyStream = orderItemList.stream().mapToInt(OrderItem::getMoney);
            int totalNum = numStream.sum();//总数量
            int totalMoney = moneyStream.sum();//订单总金额
            Map<Integer, Object> preMoneyMap = cartService.preferential(order.getUsername());//计算优惠金额
            Integer preferential = 0;
            for (Integer categoryId : preMoneyMap.keySet()) {
                Integer preMoney = (Integer) preMoneyMap.get(categoryId);
                preferential += preMoney;
            }

            order.setTotalNum(totalNum);//总数量
            order.setTotalMoney(totalMoney);//总金额
            order.setPreMoney(preferential);//优惠金额
            order.setPayMoney(totalMoney - preferential);//支付金额
            order.setCreateTime(new Date());//订单创建日期
            order.setOrderStatus("0");//订单状态,0  未付款
            order.setPayStatus("0");//支付状态: 未支付
            order.setConsignStatus("0");//发货状态: 未发货
            orderMapper.insert(order);

            //4.保存订单明细表
            for (OrderItem orderItem : orderItemList) {
                orderItem.setOrderId(order.getId());//订单主表ID
                orderItem.setId(idWorker.nextId()+"");
                orderItem.setPayMoney(orderItem.getMoney()-(Integer) preMoneyMap.get(orderItem.getCategoryId3()));//实际支付金额
                orderItemMapper.insert(orderItem);
            }
            rabbitTemplate.convertAndSend("","queue.order",order.getId());
        } catch (Exception e) {
            e.printStackTrace();
            rabbitTemplate.convertAndSend("","queue.skuback", JSON.toJSONString(orderItemList));
            throw new RuntimeException("订单生成失败");//抛出异常，让其回滚！
        }

        //5.清除购物车
        cartService.deleteCheckedCart(order.getUsername());
        //返回订单号和支付的金额
        Map<String,Object> map = new HashMap<>();
        map.put("ordersn",order.getId());
        map.put("money",order.getPayMoney());
        return map;
    }

    /**
     * 修改
     *
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public Orders findOrdersById(String id) {
        Orders orders = new Orders();
        Order order = orderMapper.selectByPrimaryKey(id);
        orders.setOrder(order);
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", id);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        orders.setOrderItemList(orderItems);
        return orders;
    }

    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private IdWorker idWorker;

    @Override
    public void batchSend(List<Order> orderList) {
        OrderLog orderLog = null;
        for (Order order : orderList) {
            if (order.getShippingName() == null || "".equals(order.getShippingName()) || order.getShippingCode() == null || "".equals(order.getShippingCode())) {
                throw new RuntimeException("请选择快递公司和填写快递单号");
            }
        }
        for (Order order : orderList) {
            order.setOrderStatus("2");
            order.setConsignStatus("1");
            Date date = new Date();
            order.setConsignTime(date);
            orderMapper.updateByPrimaryKey(order);


            orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOperater("admin");
            orderLog.setOperateTime(date);
            orderLog.setOrderId(order.getId());
            orderLog.setOrderStatus(order.getOrderStatus());
            orderLog.setPayStatus(order.getPayStatus());
            orderLog.setConsignStatus(order.getConsignStatus());
            orderLog.setRemarks(order.getTransactionId());
            orderLogMapper.insert(orderLog);
        }
    }

    @Autowired
    private OrderConfigMapper orderConfigMapper;

    @Override
    public void orderTimeOutLogic() {
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey("1");
        Integer orderTimeout = orderConfig.getOrderTimeout();
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(orderTimeout);
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThan("createTime", localDateTime);
        criteria.andEqualTo("isDelete", "0");
        criteria.andEqualTo("orderStatus", "0");
        List<Order> orderList = orderMapper.selectByExample(example);
        Order newOrder = null;
        OrderLog orderLog = null;
        for (Order order : orderList) {
            //更改订单状态
            newOrder = new Order();
            newOrder.setId(order.getId());
            newOrder.setIsDelete("1");
            newOrder.setOrderStatus("4");
            newOrder.setCloseTime(new Date());
            orderMapper.updateByPrimaryKeySelective(newOrder);


            //日志
            orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOperater("system");
            orderLog.setOperateTime(new Date());
            orderLog.setOrderId(order.getId());
            orderLog.setOrderStatus("4");
            orderLog.setPayStatus(order.getPayStatus());
            orderLog.setConsignStatus(order.getConsignStatus());
            orderLog.setRemarks("订单超时自动关闭");
            orderLogMapper.insert(orderLog);
        }
    }

    @Override
    public void merge(String orderId1, String orderId2) {
       /* Order order1 = orderMapper.selectByPrimaryKey(orderId1);
        Order order2 = orderMapper.selectByPrimaryKey(orderId2);
        order1.setTotalNum(order1.getTotalNum() + order2.getTotalNum());
        order1.setTotalMoney(order1.getTotalMoney() + order2.getTotalMoney());
        order1.setPayMoney(order1.getPreMoney() + order2.getPayMoney());
        order1.setPostFee(order1.getPostFee() + order2.getPostFee());
        order1.setPayMoney(order1.getPayMoney() + order2.getPayMoney());
        orderMapper.updateByPrimaryKeySelective(order1);

        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId2);
        List<OrderItem> orderItemList = orderItemMapper.selectByExample(example);
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderId1);
            orderItemMapper.updateByPrimaryKeySelective(orderItem);
        }

        order2.setIsDelete("1");
        orderMapper.updateByPrimaryKeySelective(order2);

        OrderLog orderLog = new OrderLog();
        orderLog.setId(idWorker.nextId() + "");
        orderLog.setOperater("admin");
        orderLog.setOperateTime(new Date());
        orderLog.setOrderId(order2.getId());
        orderLog.setOrderStatus(order2.getOrderStatus());
        orderLog.setPayStatus(order2.getPayStatus());
        orderLog.setConsignStatus(order2.getConsignStatus());
        orderLog.setRemarks("合并订单");
        orderLogMapper.insert(orderLog);*/

        Orders orders1 = findOrdersById(orderId1);
        Orders orders2 = findOrdersById(orderId2);
        //一些关于状态的判断,这里先不写
        Order order1 = orders1.getOrder();
        Order order2 = orders2.getOrder();
        //更改主订单参数
        order1.setTotalNum(order1.getTotalNum() + order2.getTotalNum());
        order1.setTotalMoney(order1.getTotalMoney() + order2.getTotalMoney());
        order1.setPayMoney(order1.getPreMoney() + order2.getPayMoney());
        order1.setPostFee(order1.getPostFee() + order2.getPostFee());
        order1.setPayMoney(order1.getPayMoney() + order2.getPayMoney());
        orderMapper.updateByPrimaryKeySelective(order1);

        CopyOnWriteArrayList<OrderItem> orderItemList1 = (CopyOnWriteArrayList) orders1.getOrderItemList();
        CopyOnWriteArrayList<OrderItem> orderItemList2 = (CopyOnWriteArrayList) orders2.getOrderItemList();
        for (OrderItem orderItem1 : orderItemList1) {
            for (OrderItem orderItem2 : orderItemList2) {
                if (orderItem1.getSkuId() == orderItem2.getSkuId()) {
                    orderItem1.setNum(orderItem1.getNum() + orderItem2.getNum());
                    orderItem1.setMoney(orderItem1.getPrice() * orderItem1.getNum());
                    orderItem1.setPayMoney(orderItem1.getPayMoney() + orderItem2.getPayMoney());
                    orderItem1.setWeight(orderItem1.getWeight() + orderItem2.getWeight());
                    orderItem1.setPostFee(orderItem1.getPostFee() + orderItem2.getPostFee());
                    orderItemList2.remove(orderItem2);
                    orderItemMapper.updateByPrimaryKeySelective(orderItem1);
                }
            }
        }
        for (OrderItem orderItem : orderItemList2) {
            orderItem.setOrderId(orderId1);
            orderItemMapper.updateByPrimaryKeySelective(orderItem);
        }
        order2.setIsDelete("1");
        orderMapper.updateByPrimaryKeySelective(order2);

        OrderLog orderLog = new OrderLog();
        orderLog.setId(idWorker.nextId() + "");
        orderLog.setOperater("admin");
        orderLog.setOperateTime(new Date());
        orderLog.setOrderId(order2.getId());
        orderLog.setOrderStatus(order2.getOrderStatus());
        orderLog.setPayStatus(order2.getPayStatus());
        orderLog.setConsignStatus(order2.getConsignStatus());
        orderLog.setRemarks("合并订单");
        orderLogMapper.insert(orderLog);

    }

    @Override
    public void split(List<OrderItem> orderItemList) {
       /* Integer sizeSum = 0;
        for (OrderSize orderSize : orderSizeList) {
            sizeSum += orderSize.getOrderSize();
        }
        String orderId = orderSizeList.get(0).getOrderId();
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (sizeSum > order.getTotalNum()) {
            throw new RuntimeException("拆分数目超出最大数量");
        }
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectByExample(example);
        Order newOrder = null;
        for (OrderSize orderSize : orderSizeList) {
            newOrder = new Order();
            try {
                BeanUtils.copyProperties(newOrder,order);
            } catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException("属性拷贝出错");
            }
            if (orderSize.getOrderId() != null) {
                newOrder.setId(orderSize.getOrderId());
            }else {
                newOrder.setId(idWorker.nextId()+"");
            }
            newOrder.setTotalNum(0);
            newOrder.setTotalMoney(0);
            newOrder.setPreMoney(0);
            newOrder.setPostFee(0);
            newOrder.setPayMoney(0);
            OrderItem orderItem = null;
            for (Integer i = 0; i < orderSize.getOrderSize(); i++) {
                orderItem = orderItemList.remove(i.intValue());
                newOrder.setTotalNum(newOrder.getTotalNum()+orderItem.getNum());
                newOrder.setTotalMoney(newOrder.getTotalMoney()+orderItem.getMoney());
                newOrder.setPayMoney(newOrder.getPayMoney()+orderItem.getPayMoney());
                newOrder.setPostFee(newOrder.getPostFee()+orderItem.getPostFee());

                orderItem.setOrderId(newOrder.getId());
                orderItemMapper.updateByPrimaryKeySelective(orderItem);
            }
            newOrder.setPreMoney(newOrder.getTotalMoney()-newOrder.getPayMoney());
            if (orderSize.getOrderId() != null) {
                orderMapper.updateByPrimaryKeySelective(newOrder);
            }else {
                orderMapper.insert(newOrder);
            }
        }*/
        if (orderItemList == null || orderItemList.size() == 0) {
            throw new RuntimeException("请传入要分的订单");
        }
        OrderItem newOrderItem = null;
        OrderItem reaOrderItem = null;
        Order oldOrder = null;
        List<OrderItem> orderItems = new ArrayList<>();
        String orderItemId = "";
        String orderId = orderItemList.get(0).getOrderId();
        for (OrderItem oldOrderItem : orderItemList) {
            orderItemId = oldOrderItem.getId();
            reaOrderItem = orderItemMapper.selectByPrimaryKey(orderItemId);
            //真实订单中商品数目
            Integer reaNum = reaOrderItem.getNum();
            //传入的要拆分的订单
            Integer oldNum = oldOrderItem.getNum();
            if (reaNum < oldNum || oldNum <= 0) {
                throw new RuntimeException("传入要拆分的订单数目错误");
            }
            newOrderItem = new OrderItem();
            try {
                BeanUtils.copyProperties(reaOrderItem, newOrderItem);
                BeanUtils.copyProperties(reaOrderItem, oldOrderItem);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("属性拷贝出错");
            }
            //设置新订单明细属性
            newOrderItem.setId(idWorker.nextId() + "");
            newOrderItem.setNum(reaNum - oldNum);
            newOrderItem.setMoney(newOrderItem.getPrice() * newOrderItem.getNum());
            newOrderItem.setWeight((reaOrderItem.getWeight() * newOrderItem.getNum() / reaNum));
            newOrderItem.setPostFee(reaOrderItem.getPostFee() * newOrderItem.getNum() / reaNum);
            newOrderItem.setPayMoney(newOrderItem.getMoney() + newOrderItem.getPostFee());
            orderItems.add(newOrderItem);
            //设置旧订单明细属性
            oldOrderItem.setNum(oldNum);
            oldOrderItem.setMoney(oldOrderItem.getPrice() * oldOrderItem.getNum());
            oldOrderItem.setWeight(reaOrderItem.getWeight() * oldOrderItem.getNum() / reaNum);
            oldOrderItem.setPostFee(reaOrderItem.getPostFee() * oldOrderItem.getNum() / reaNum);
            oldOrderItem.setPayMoney(oldOrderItem.getMoney() + oldOrderItem.getPostFee());
            orderItemMapper.updateByPrimaryKeySelective(oldOrderItem);
        }
        //获取主订单
        Order order1 = orderMapper.selectByPrimaryKey(orderId);
        order1.setTotalNum(0);
        order1.setTotalMoney(0);
        order1.setPreMoney(0);
        order1.setPostFee(0);
        order1.setPayMoney(0);
        //新建新订单
        Order order2 = new Order();
        try {
            BeanUtils.copyProperties(order1, order2);
            order2.setId(idWorker.nextId() + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (OrderItem orderItem : orderItemList) {
            order1.setTotalNum(order1.getTotalNum() + orderItem.getNum());
            order1.setTotalMoney(order1.getTotalMoney() + orderItem.getMoney());
            order1.setPayMoney(order1.getPayMoney() + orderItem.getPayMoney());
            order1.setPostFee(order1.getPostFee() + orderItem.getPostFee());
            order1.setPreMoney(order1.getTotalMoney() - orderItem.getPayMoney());
        }
        orderMapper.updateByPrimaryKeySelective(order1);

        for (OrderItem orderItem : orderItems) {
            orderItem.setOrderId(order2.getId());
            order2.setTotalNum(order2.getTotalNum() + orderItem.getNum());
            order2.setTotalMoney(order2.getTotalMoney() + orderItem.getMoney());
            order2.setPayMoney(order2.getPayMoney() + orderItem.getPayMoney());
            order2.setPostFee(order2.getPostFee() + orderItem.getPostFee());
            order2.setPreMoney(order2.getTotalMoney() - orderItem.getPayMoney());
            orderItemMapper.updateByPrimaryKeySelective(orderItem);
        }
        orderMapper.insert(order2);
    }

    @Override
    @Transactional
    public void updatePayStatus(String orderId, String transactionId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order != null && "0".equals(order.getPayStatus())) {//存在订单且支付状态为0
            order.setPayStatus("1");
            order.setOrderStatus("1");
            order.setUpdateTime(new Date());
            order.setPayTime(new Date());
            order.setTransactionId(transactionId);
            orderMapper.updateByPrimaryKeySelective(order);
            //订单变动日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId()+"");
            orderLog.setOperater("system");//系统
            orderLog.setOperateTime(new Date());//当前日期
            orderLog.setOrderStatus("1");
            orderLog.setPayStatus("1");
            orderLog.setRemarks("支付流水号"+transactionId);
            orderLog.setOrderId(order.getId());
            orderLogMapper.insert(orderLog);
        }
    }

    @Autowired
    private WeixinPayService weixinPayService;


    @Override
    @Transactional
    public void closeOrderByOrderId(String orderId) {
        Order order = findById(orderId);
        if (order != null) {
            Map map = weixinPayService.closeWXOrderByOrderId(orderId);
            if ("SUCCESS".equals(map.get("return_code"))) {
                try {
                    order.setUpdateTime(new Date());
                    order.setOrderStatus("4");
                    orderMapper.insert(order);
                    //回复商品表库存
                    Example example = new Example(OrderItem.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("orderId", orderId);
                    List<OrderItem> orderItems = orderItemMapper.selectByExample(criteria);
                    skuService.replyInventory(orderItems);
                    //记录订单日志
                    OrderLog orderLog = new OrderLog();
                    orderLog.setId(idWorker.nextId()+"");
                    orderLog.setOrderId(orderId);
                    orderLog.setPayStatus("0");
                    orderLog.setRemarks("订单支付超时自动关闭");
                    orderLog.setOrderStatus("4");
                    orderLog.setOperater("system");
                    orderLog.setOperateTime(new Date());
                    orderLog.setConsignStatus("0");
                    orderLogMapper.insert(orderLog);
                } catch (Exception e) {
                    e.printStackTrace();
                    //记录订单日志
                    OrderLog orderLog = new OrderLog();
                    orderLog.setId(idWorker.nextId()+"");
                    orderLog.setOrderId(orderId);
                    orderLog.setPayStatus("0");
                    orderLog.setRemarks("关闭订单失败,请联系人工处理");
                    orderLog.setOrderStatus("4");
                    orderLog.setOperateTime(new Date());
                    orderLog.setConsignStatus("0");
                    orderLogMapper.insert(orderLog);
                }
            }else{
                throw new RuntimeException((String) map.get("result_msg"));
            }
        }else {
            throw new RuntimeException("没有对应订单");
        }

    }

    /**
     * 构建查询条件
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 订单id
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andLike("id", "%" + searchMap.get("id") + "%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if (searchMap.get("payType") != null && !"".equals(searchMap.get("payType"))) {
                criteria.andLike("payType", "%" + searchMap.get("payType") + "%");
            }
            // 物流名称
            if (searchMap.get("shippingName") != null && !"".equals(searchMap.get("shippingName"))) {
                criteria.andLike("shippingName", "%" + searchMap.get("shippingName") + "%");
            }
            // 物流单号
            if (searchMap.get("shippingCode") != null && !"".equals(searchMap.get("shippingCode"))) {
                criteria.andLike("shippingCode", "%" + searchMap.get("shippingCode") + "%");
            }
            // 用户名称
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andLike("username", "%" + searchMap.get("username") + "%");
            }
            // 买家留言
            if (searchMap.get("buyerMessage") != null && !"".equals(searchMap.get("buyerMessage"))) {
                criteria.andLike("buyerMessage", "%" + searchMap.get("buyerMessage") + "%");
            }
            // 是否评价
            if (searchMap.get("buyerRate") != null && !"".equals(searchMap.get("buyerRate"))) {
                criteria.andLike("buyerRate", "%" + searchMap.get("buyerRate") + "%");
            }
            // 收货人
            if (searchMap.get("receiverContact") != null && !"".equals(searchMap.get("receiverContact"))) {
                criteria.andLike("receiverContact", "%" + searchMap.get("receiverContact") + "%");
            }
            // 收货人手机
            if (searchMap.get("receiverMobile") != null && !"".equals(searchMap.get("receiverMobile"))) {
                criteria.andLike("receiverMobile", "%" + searchMap.get("receiverMobile") + "%");
            }
            // 收货人地址
            if (searchMap.get("receiverAddress") != null && !"".equals(searchMap.get("receiverAddress"))) {
                criteria.andLike("receiverAddress", "%" + searchMap.get("receiverAddress") + "%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if (searchMap.get("sourceType") != null && !"".equals(searchMap.get("sourceType"))) {
                criteria.andLike("sourceType", "%" + searchMap.get("sourceType") + "%");
            }
            // 交易流水号
            if (searchMap.get("transactionId") != null && !"".equals(searchMap.get("transactionId"))) {
                criteria.andLike("transactionId", "%" + searchMap.get("transactionId") + "%");
            }
            // 订单状态
            if (searchMap.get("orderStatus") != null && !"".equals(searchMap.get("orderStatus"))) {
                criteria.andLike("orderStatus", "%" + searchMap.get("orderStatus") + "%");
            }
            // 支付状态
            if (searchMap.get("payStatus") != null && !"".equals(searchMap.get("payStatus"))) {
                criteria.andLike("payStatus", "%" + searchMap.get("payStatus") + "%");
            }
            // 发货状态
            if (searchMap.get("consignStatus") != null && !"".equals(searchMap.get("consignStatus"))) {
                criteria.andLike("consignStatus", "%" + searchMap.get("consignStatus") + "%");
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andLike("isDelete", "%" + searchMap.get("isDelete") + "%");
            }

            // 数量合计
            if (searchMap.get("totalNum") != null) {
                criteria.andEqualTo("totalNum", searchMap.get("totalNum"));
            }
            // 金额合计
            if (searchMap.get("totalMoney") != null) {
                criteria.andEqualTo("totalMoney", searchMap.get("totalMoney"));
            }
            // 优惠金额
            if (searchMap.get("preMoney") != null) {
                criteria.andEqualTo("preMoney", searchMap.get("preMoney"));
            }
            // 邮费
            if (searchMap.get("postFee") != null) {
                criteria.andEqualTo("postFee", searchMap.get("postFee"));
            }
            // 实付金额
            if (searchMap.get("payMoney") != null) {
                criteria.andEqualTo("payMoney", searchMap.get("payMoney"));
            }

        }
        return example;
    }

}
